package model

import (
	"errors"
	"github.com/jinzhu/gorm"
	"naio/db/mysql"
)

// 商城Banner
type BannerModel struct {
	Model
	Picture      string // 图片
	Name         string // 名称
	BusinessType int    // 业务类型：1-商品
	BusinessId   int    // 业务主键
	Status       int    // 是否显示：0-否 1-是
	Del          int
}

func (BannerModel) TableName() string {
	return "banner"
}

func BrowseBanner(status, page, size int) (*[]BannerModel, error){
	var list []BannerModel
	db := mysql.GetMysqlPool().GetMysqlDB()
	err := db.Where("del=0 AND status=?", status).Offset((page - 1) * size).Limit(size).Order("sort").Find(&list).Error
	if err != nil {
		return nil, err
	}
	return &list, nil
}

func CountBanner(status int) int {
	var total int
	db := mysql.GetMysqlPool().GetMysqlDB()
	db.Table("banner").Where("del=0 AND status=?", status).Count(&total)
	return total
}

func GetBannerByID(id int) (*BannerModel, error){
	one := &BannerModel{}
	db := mysql.GetMysqlPool().GetMysqlDB()
	err := db.Where("id=?", id).First(&one).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, errors.New("banner不存在")
		}else{
			return nil, err
		}
	}
	return one, nil
}

func CreateBanner(banner *BannerModel) error{
	db := mysql.GetMysqlPool().GetMysqlDB()
	err:=db.Create(banner).Error
	if err != nil {
		return err
	}
	return nil
}

func SaveBanner(banner *BannerModel) error{
	db := mysql.GetMysqlPool().GetMysqlDB()
	err:=db.Save(banner).Error
	if err != nil {
		return err
	}
	return nil
}